package vn.orderonline.web.admin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import vn.orderonline.com.core.business.category.ICategory;
import vn.orderonline.com.core.business.common.ICommon;
import vn.orderonline.com.core.business.dto.DistrictDto;
import vn.orderonline.com.core.business.dto.RestaurantDto;
import vn.orderonline.com.core.business.restaurant.IRestaurantManager;
import vn.orderonline.core.commons.utils.StringUtils;

@Controller
@RequestMapping("/restaurant")
public class RestaurantController {
	
	private static final Logger LOGGER = Logger.getLogger(RestaurantController.class);

	@Autowired
	private IRestaurantManager iRestaurantManager;
	@Autowired
	private ICategory iCategory;
	@Autowired
	private ICommon iCommon;
	
	@RequestMapping(value = "/list", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public String getListRestautaurant(ModelMap model, HttpServletRequest request) {
		if (request.getUserPrincipal() != null) {
			LOGGER.info("GET LIST OF RESTAURANTS!");
			List<RestaurantDto> list = null;
			RestaurantDto objSearch = null;
			try {
				list = iRestaurantManager.getAllRestaurants();
				model.addAttribute("list", list);
				objSearch = new RestaurantDto();
				model.addAttribute("objSearch", objSearch);
			} catch (Exception e) {
				LOGGER.error("ERROR WHEN GET LIST OF RESTAURANTS!", e);
			}
			LOGGER.info("END GET LIST OF RESTAURANTS!");
		}
		return request.getUserPrincipal() != null ? "/restaurant/searchrestaurant" : "redirect:/adminaccount/login";
	}
	
	@RequestMapping(value = "/search", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public ModelAndView search(@ModelAttribute RestaurantDto objSearch, HttpServletRequest request) {
		LOGGER.info("START SEARCH RESTAURANT!");
		ModelAndView mv = null;
		try {
			if (request.getUserPrincipal() != null) {
				mv = new ModelAndView("/restaurant/searchrestaurant");
				mv.addObject("list", iRestaurantManager.search(objSearch));
				mv.addObject("objSearch", objSearch);
			} else {
				mv = new ModelAndView("redirect:/adminaccount/login");
			}
		} catch (Exception e) {
			LOGGER.info("ERROR WHEN SEARCH RESTAURANT!", e);
		}
		LOGGER.info("END SEARCH RESTAURANT!");
		return mv;
	}
	
//	@RequestMapping(value = "/detail/{restaurantId}", method = RequestMethod.GET)
//	public ModelAndView detail(@PathVariable Integer restaurantId) {
//		LOGGER.info("START VIEW DETAIL RESTAURANT!" + "restaurantId = " + restaurantId);
//		ModelAndView mv = null;
//		try {
//			mv = new ModelAndView("/restaurant/detailrestaurant");
//			mv.addObject("res", iRestaurantManager.getRestaurantById(restaurantId));
//		} catch (Exception e) {
//			LOGGER.error("ERROR WHEN VIEW DETAIL RESTAURANT!", e);
//		}
//		LOGGER.info("END VIEW DETAIL RESTAURANT!");
//		return mv;
//	}
//	
	@RequestMapping(value = "/detail", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public String detail(@RequestParam(value="restaurantId", required = true) Integer restaurantId, ModelMap model, HttpServletRequest request) {
		LOGGER.info("START VIEW DETAIL RESTAURANT!" + "restaurantId = " + restaurantId);
		try {
			model.addAttribute("res", iRestaurantManager.getRestaurantById(restaurantId, "detail"));
		} catch (Exception e) {
			LOGGER.error("ERROR WHEN VIEW DETAIL RESTAURANT!", e);
		}
		LOGGER.info("END VIEW DETAIL RESTAURANT!");
		return request.getUserPrincipal() != null ? "/restaurant/detailrestaurant" : "redirect:/adminaccount/login";
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public String delete(@RequestParam(value = "restaurantId", required = true) Integer restaurantId, HttpServletRequest request) {
		LOGGER.info("START DELETE RESTAURANT!");
		try {
			iRestaurantManager.delete(restaurantId);
		} catch (Exception e) {
			LOGGER.error("ERROR WHEN DELETE RESTAURANT!", e);
		}
		LOGGER.info("END DELETE RESTAURANT!");
		return request.getUserPrincipal() != null ? "redirect:/restaurant/list" : "redirect:/adminaccount/login";
	}
	
	@RequestMapping(value="/form", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public String formAdd(ModelMap model, HttpServletRequest request) {
		LOGGER.info("CREATE FORM REGISTER RESTAURANT!");
		try {
			model.addAttribute("res", new RestaurantDto());
			model.addAttribute("cityList", iCommon.cityList());
			model.addAttribute("categoryList", iCategory.getListCategory());
		} catch (Exception e) {
			LOGGER.error("ERROR WHEN CREATE FORM REGISTER RESTAURANT!");
		}
		LOGGER.info("END CREATE FORM REGISTER RESTAURANT!");
		return request.getUserPrincipal() != null ? "/restaurant/addrestaurant" : "redirect:/adminaccount/login";
	}
		
	@RequestMapping(value="/add", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
	public String create(RestaurantDto res, HttpServletRequest request) {
		if (request.getUserPrincipal() != null) {
			res.setCreateId(request.getUserPrincipal().getName());
			LOGGER.info("START ADD RESTAURANT!");
			try {
			 	iRestaurantManager.add(res);
			} catch (Exception e) {
				LOGGER.error("ERROR WHEN ADD RESTAURANT!", e);
			}
			LOGGER.info("END ADD RESTAURANT!");
		}
		return request.getUserPrincipal() != null ? "redirect:list" : "redirect:/adminaccount/login";
	}
	
	@RequestMapping(value = "/updateform", method = RequestMethod.GET)
	public ModelAndView formUpdate(@RequestParam(value = "restaurantId", required = true) Integer restaurantId, HttpServletRequest request) {
		LOGGER.info("START CREATE FORM UPDATE RESTAURANT!");
		ModelAndView mv = null;
		RestaurantDto dto = null;
		try {
			dto = iRestaurantManager.getRestaurantById(restaurantId, "update");
			if (request.getUserPrincipal() != null) {
				mv = new ModelAndView("/restaurant/updaterestaurant");
				mv.addObject("res", dto);
				mv.addObject("cityList", iCommon.cityList());
				mv.addObject("districtList", iCommon.districMap(dto.getCityId()));
				mv.addObject("categoryList", iCategory.getListCategory());
			} else {
				mv = new ModelAndView("redirect:/adminaccount/login");
			}
		} catch (Exception e) {
			LOGGER.error("ERROR WHEN CREATE FORM UPDATE RESTAURANT!", e);
		}
		LOGGER.info("END WHEN CREATE UPDATE FORM UPDATE RESTAURANT!");
		return mv;
	}
	
	@RequestMapping(value = "/update/{restaurantId}", method = RequestMethod.POST, produces = "applications/json;charset=UTF-8")
	public String update(@ModelAttribute RestaurantDto res, @PathVariable Integer restaurantId, HttpServletRequest request) {
		if (request.getUserPrincipal() != null) {
			LOGGER.info("START UPDATE RESTAURANT!");
			try {
				res.setRestaurantId(restaurantId);
				res.setUpdateId(request.getUserPrincipal().getName());
				iRestaurantManager.update(res);
			} catch (Exception e) {
				LOGGER.error("ERROR WHEN UPDATE RESTAURANT!", e);
			}
			LOGGER.info("END UPDATE RESTAURANT!");
			}
		return request.getUserPrincipal() != null ? "redirect:/restaurant/list" : "redirect:/adminaccount/login";
	}
	
	@RequestMapping(value = "/checkexistedrestaurant", method = RequestMethod.POST)//, produces = "application/json;charset=UTF-8")
	@ResponseBody public String checkExistedRestaurant(@RequestParam String restaurantName) {
		LOGGER.info("START CHECK EXISTED RESTAURANT NAME!");
		Boolean flag = false;
		try {
			flag = iRestaurantManager.checkExistedRestaurant(restaurantName);
		} catch (Exception e) {
			LOGGER.error("ERROR WHEN CHECK EXISTED RESTAURANT NAME!");
		}
		LOGGER.info("END CHECK EXISTED RESTAURANT NAME!" + flag.toString());
		
		return flag.toString();
	}
	
	@RequestMapping(value = "/getdistrictbycityid", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public String getDistrictByCityId(@RequestParam Integer cityId) {
		LOGGER.info("START GET DISTRICT BY CIATY ID!");
		List<DistrictDto> list = null;
		String str = null;
		try {
			list = iCommon.districtList(cityId);
			str = StringUtils.parseToJSON(list);
		} catch (Exception e) {
			LOGGER.error("ERROR WHEN GET DISTRICT BY CITY ID!", e);
		}
		LOGGER.info("END GET DISTRICT BY CITY ID!");
		return str;
	}
	
}
